package com.softer.chengxin.param.controller;

import com.softer.chengxin.common.domin.Common;
import com.softer.chengxin.common.domin.CommonResult;
import com.softer.chengxin.common.enums.ResultEnum;
import com.softer.chengxin.login.service.impl.LoginServiceimpl;
import com.softer.chengxin.param.entity.Grade;
import com.softer.chengxin.param.service.GradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 评级
 *
 * @author Gong Zhiyang
 * @date 2019/12/14
 */
@RestController
@RequestMapping("/api/grade")
public class GradeController {
    @Autowired
    private GradeService gradeService;
    @Autowired
    private LoginServiceimpl loginService;

    /**
     * 保存评级设置，根据主键，有则修改，无则增加
     *
     * @param list    评级集合
     * @param session session
     * @return 保存结果
     */
    @PostMapping("/save")
    public CommonResult save(@RequestBody List<Grade> list, HttpSession session) {
        //  登录名
        String loginName = (String) session.getAttribute(Common.LOGIN_NAME);
        CommonResult result = loginService.checkLoginName(loginName);
        if (ResultEnum.FAIL.getCode() == result.getData()) {
            return result;
        }
        return gradeService.save(list, loginName);
    }

    /**
     * 获取评级列表
     *
     * @return 列表
     */
    @PostMapping("/getList")
    public List<Grade> getList(HttpSession session) {
        //  登录名
        String loginName = (String) session.getAttribute(Common.LOGIN_NAME);
        CommonResult result = loginService.checkLoginName(loginName);
        if (ResultEnum.FAIL.getCode() == result.getData()) {
            return new ArrayList<>();
        }
        return gradeService.getList();
    }

    /**
     * 删除评级
     *
     * @param id      评级ID
     * @param session session
     * @return 删除结果
     */
    @PostMapping("/delete")
    public CommonResult delete(int id, HttpSession session) {
        //  登录名
        String loginName = (String) session.getAttribute(Common.LOGIN_NAME);
        CommonResult result = loginService.checkLoginName(loginName);
        if (ResultEnum.FAIL.getCode() == result.getData()) {
            return result;
        }
        return gradeService.delete(id);
    }

    /**
     * 查询信用等级列表
     * 用于下拉列表
     *
     * @return 信用等级下拉列表
     */
    @PostMapping("/getLevelList")
    public List<String> getLevelList() {
        return gradeService.getLevelList();
    }
}
